package cn.dapeng.features;

import cn.dapeng.util.SleepingUtil;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;


/**
 * ReentrantLock高级用法：
 * 可以试图获取锁，在指定的时间内 可以通过tryLock方法
 */
public class ReentrantLock_T03 {

    static ReentrantLock lock = new ReentrantLock();

    public static void k1() {
        lock.lock();
        try {
            for (int i = 0; i < 3; i++) {
                SleepingUtil.sleep(1, TimeUnit.SECONDS);
                System.out.println(Thread.currentThread().getName() + " : " + i);
            }
        } finally {
            lock.unlock();
        }
    }

    public static void k2() {
        boolean isLocked = false;
        try {
            isLocked = lock.tryLock(5, TimeUnit.SECONDS);
            System.out.println(Thread.currentThread().getName() + " : " + isLocked);
        } catch (InterruptedException e) {
            System.err.println(Thread.currentThread().getName() + " interrupted!");
        } finally {
            if (isLocked) {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) throws Exception {

        Thread k1 = new Thread(ReentrantLock_T03::k1, "k1");
        k1.start();
        SleepingUtil.sleep(1, TimeUnit.SECONDS);

        Thread k2 = new Thread(ReentrantLock_T03::k2, "k2");
        k2.start();

        k1.join();

    }
}
